<!--
 * @Author: 1453937336@qq.com 1453937336@qq.com
 * @Date: 2024-04-17 10:06:59
 * @LastEditors: 1453937336@qq.com 1453937336@qq.com
 * @LastEditTime: 2024-07-16 17:04:10
 * @FilePath: \itforce_hris\src\views\system\dept\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <a-spin :spinning="spinning">
    <a-row v-show="!ifChart">
      <a-col :span="6" class="treeCol">
        <tree
          ref="treeRef"
          :menuList="menuList"
          :treeData="treeData"
          :id="companyId"
          :parentId="parentIds"
          :positionTypeList="positionTypeList"
          @treeEmint="treeEmint"
          @companyIdChange="companyIdChange"
          @positionTypeChange="positionTypeChange"
        />
      </a-col>
      <a-col :span="18" class="information">
        <a-row type="flex" justify="space-between" v-if="!ifEmployee">
          <a-col :span="24" style="display: flex">
            <i class="fa fa-indent" style="margin-top: 5px" />
            <a-breadcrumb
              style="margin-left: 8px; margin-right: 8px"
              separator=">"
            >
              <a-breadcrumb-item>{{ companyObj.name }}</a-breadcrumb-item>
              <a-breadcrumb-item v-for="(item, index) in breadcrumbList">{{
                item
              }}</a-breadcrumb-item>
            </a-breadcrumb>
          </a-col>
          <a-col :span="24" style="display: flex; justify-content: flex-end">
            <a-button
              v-if="!ifPosition"
              style="margin-right: 8px; font-size: 12px"
              @click="orgChart"
              :disabled="organizationDisabled"
            >
              <i
                class="fa fa-sitemap"
                style="margin-right: 4px; margin-left: 4px"
              />
              {{ $t("组织架构图") }}
            </a-button>
            <a-button
              v-if="!isVirtual"
              style="font-size: 12px; margin-right: 8px"
              @click="onUnitCilck"
              v-permission="['createFlag']"
            >
              +
              <i
                class="fa fa-cogs"
                style="margin-right: 4px; margin-left: 4px"
              />
              {{  $t("组织") }} {{ $t("单元") }}
            </a-button>
            <a-button
              style="font-size: 12px; margin-right: 8px; margin-left: 8px"
              v-permission="['export']"
              type="default"
              @click="exportClick"
            >
              <i
                class="fa fa-download"
                style="margin-left: 4px; margin-right: 4px"
              />{{ $t("导出") }}
            </a-button>
            <!-- <upload
              v-permission="['import']"
              :fileType="'export'"
              pageName="organizatioin"
              :enterpriseId="companyId"
              @refresh="DeleteUnitModal"
            ></upload> -->
            <importFile :fileType="'export'" pageName="organizatioin" :enterpriseId="companyId"/>
          </a-col>
        </a-row>
        <component
          :is="isComponent"
          :companyObj="companyObj"
          :unitObj="unitObj"
          :companyId="companyId"
          @updateUnitInformationRefresh="updateUnitInformationRefresh"
          @DeleteUnitModal="DeleteUnitModal"
          @employeeClose="employeeClose"
        >
        </component>
      </a-col>
    </a-row>
    <a-row v-if="ifChart">
      <a-col :span="24">
        <organizationChart
          ref="orgChartRef"
          @close="onClose"
          :treeData="organizationTree"
        />
      </a-col>
    </a-row>

    <unitModal
      ref="unitModalRef"
      :isIfTree="isIfTree"
      @addUnitModal="addUnitModal"
    />
  </a-spin>
</template>

<script setup>
import { Local, Session } from "@/utils/storage";
import {
  reactive,
  ref,
  watch,
  onMounted,
  defineAsyncComponent,
  nextTick,
  computed,
} from "vue";
import { h } from "vue";
import { Modal } from 'ant-design-vue';
import { createVNode } from 'vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
// import upload from "@/components/upload/index.vue";
import importFile from "@/components/import-file/index.vue";
import corporateInformation from "./components/corporate-information.vue";
import unitInformation from "./components/unit-information.vue";
import unitModal from "./components/unit-modal.vue";
import tree from "@/components/itfor-tree/index.vue";
import organizationChart from "./components/organization-chart.vue";
import {
  GetEnterpriseList,
  GetEnterpriseDetails,
  GetBusinessUnit,
  GetBusinessUnitTree,
  GetParentBuName,
  PostOrganizationExport,
} from "@/api/organization/index";
// const tree = defineAsyncComponent(() => import('@/components/itfor-tree/index.vue'))
import { useLanguage } from "@/hooks/index";
import { GetBatchCodeDict } from "@/api/public";
const { isEn, isCn, isArabic } = useLanguage();
import * as XLSX from "xlsx";
import { useI18n } from "vue-i18n";
const { t: $t } = useI18n();
// 公司id
const companyId = ref(null);
const companyUuid = ref(null);
// tree-top 公司切换
const companyObj = ref({});
const breadcrumbList = ref([]); // 导航栏tree
const companyIdChange = (obj) => {
  // consolelog('公司切换', obj)
  companyUuid.value = obj.uuid;
  companyId.value = obj.id;
  breadcrumbList.value = []; // 导航栏tree赋值为空
  getCompanyDetails();
  treeEmint(false);
  getTree();
};
// 查看公司详情
const getCompanyDetails = () => {
  GetEnterpriseDetails({
    uuid: companyUuid.value,
  }).then((res) => {
    if (res.code !== 200) return;
    nextTick(() => {
      companyObj.value = res.data;
    });
  });
};
const positionTypeList = ref([]);
const getCode = () => {
  GetBatchCodeDict({
    dictKey: "positionType",
  }).then((res) => {
    if (res.code !== 200) return;
    positionTypeList.value = res.data.positionType;
  });
};

const cancel = () => {
  // 设置一个函数，在执行请求前先执行这个函数
  // 获取缓存的 请求取消标识 数组，取消所有关联的请求
  let cancelArr = window.axiosCancel;
  cancelArr.forEach((ele, index) => {
    // ele.cancel("取消了请求") // 在失败函数中返回这里自定义的错误信
    console.log("取消了请求");
    delete window.axiosCancel[index];
  });
};
// 树tree
const treeData = ref([]);
const treeAllData = ref([]);
const organizationTree = ref([]); // 传到组织结构图里面的树
const unitObj = ref({});
const isComponent = ref(corporateInformation);
const isIfTree = ref(false);
const treeEmint = (ifTree, selectTree) => {
  if (ifTree) {
    // 树的集合、选中树的obj对象
    isIfTree.value = true;
    isComponent.value = unitInformation;
    nextTick(() => {
      unitObj.value = selectTree;
     
      console.log("--------点击子集------", selectTree);
      if (selectTree) {
        getParentName(selectTree.uuid);
        getSelectChaild(selectTree.id);
      }
    });
  } else {
    isIfTree.value = false;
    breadcrumbList.value = []; // 导航栏tree赋值为空
    isComponent.value = corporateInformation;
    getCompanyDetails();
    // getAllTree()
  }
};
const isVirtual = computed(() => {
  return unitObj.value.isVirtual
});


const positionTypeVule = ref(0);
const positionTypeChange = async (val) => {
  positionTypeVule.value = val;
  addUnitModal();
};

const getSelectChaild = async (id) => {
  organizationTree.value = [];
  await GetBusinessUnitTree({
    enterpriseId: companyId.value,
    includeLeader: true,
    includePosition: true,
    id: id,
    positionType: positionTypeVule.value, // 0名义岗位1实际岗位
  }).then((res) => {
    organizationTree.value = res.data;
    console.log("organizationTree.value===>>>>", organizationTree.value);
  });
};

// 判断组织架构图按钮是否显示
const organizationDisabled = computed(() => {
  return !isIfTree.value || organizationTree.value[0]?.children === null
});
// 根据uuid查询父级bu名称
const getParentName = (uuid) => {
  GetParentBuName(uuid).then((res) => {
    if (res.data) {
      const list = isCn.value
        ? res.data.nameZh.split("/").filter((item) => item)
        : isArabic.value
        ? res.data.nameAr.split("/").filter((item) => item)
        : res.data.nameEn.split("/").filter((item) => item);
      breadcrumbList.value = list;
    }
  });
};

const ifChart = ref(false);
const orgChart = () => {
  ifChart.value = true;
};
// 关闭组织架构图
const onClose = (v) => {
  ifChart.value = v;
  // getSelectChaild(unitObj.value.id)
};

// 初始化
onMounted(() => {
  getMenuList();
  getCode();
});
const menuList = ref([]);
const getMenuList = () => {
  GetEnterpriseList().then((res) => {
    if (res.code !== 200) return;
    menuList.value = res.data;
    companyId.value = menuList.value[0].id;
    companyUuid.value = menuList.value[0].uuid;
    getCompanyDetails();
    getTree();
  });
};
// 树
const spinning = ref(false);
const getTree = async () => {
  spinning.value = true;
  await GetBusinessUnitTree({
    enterpriseId: companyId.value,
    includeLeader: true,
    fromTree: true,
    includePosition: positionTypeVule.value === 0 ? true : false,
    positionType: positionTypeVule.value, // 0名义岗位1实际岗位
  }).then((res) => {
      if (positionTypeVule.value === 0) {
        nextTick(() => {
          const list = trav(cloneDeep(res.data));
          treeData.value = convertValuesToString(list)
          console.log("treeData.value", treeData.value);
        });
      } else {
        nextTick(() => {
          treeData.value = res.data;
        });
      }
  }).finally(() => {
    spinning.value = false;
  });
};

const convertValuesToString = (tree) => {
  return tree.map((node) => {
    const convertedNode = { ...node };
    if (convertedNode.children) {
      convertedNode.children = convertValuesToString(convertedNode.children);
    }
    convertedNode.nameEn = convertedNode.nameEn || convertedNode.name
    convertedNode.nameAr = convertedNode.nameAr || convertedNode.name
    convertedNode.nameZh = convertedNode.nameZh || convertedNode.name
    convertedNode.unitTypeIcon = convertedNode.unitTypeIcon || "card"
    convertedNode.isVirtual = convertedNode.isVirtual || false
    return convertedNode;
  });
};

function trav(list) {
  for (let i = 0; i < list.length; i++) {
    const element = list[i];
    if (element.positionList) {
      const arr = element.positionList.map((k) => {
        k.unitTypeIcon = "card";
        k.nameEn = k.name;
        k.nameAr = k.name;
        k.nameZh = k.name;
        k.isVirtual = true
        return k;
      });
      if (element.children) {
        element.children.push(...arr);
      }
      if (!element.children) {
        element.children = arr;
      }
      delete element.positionList;
    }
    if (Array.isArray(element.children)) trav(element.children);
  }
  return list;
}

const ifPosition = computed(() => {
  return positionTypeVule.value === 0
});


// 有公司的树
// const getAllTree = () => {
//   GetBusinessUnitTree({
//     enterpriseId: companyId.value,
//     includeEnterprise: true
//   }).then(res => {
//     treeAllData.value = res.data
//   })
// }

// 单元
const unitModalRef = ref(null);
const unitParams = ref({});
const onUnitCilck = () => {
  if (isIfTree.value) unitParams.value = unitObj.value;
  else unitParams.value = companyObj.value;
  if (unitModalRef.value)
    unitModalRef.value.showModal(companyId.value, unitParams.value);
};
// 刷新tree
const treeRef = ref(null);
const addUnitModal = () => {
  getTree();
  treeEmint(isIfTree.value, unitObj.value);
};
// 根据id查tree的节点
const findNodeById = (tree, id) => {
  for (let node of tree) {
    if (node.id === id) {
      return node;
    }
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) {
        return found;
      }
    }
  }
  return undefined;
};
const parentIds = ref();
const updateUnitInformationRefresh = async (parentId, id) => {
  await getTree();
  nextTick(() => {
    parentIds.value = parentId;
  });
  const findTree = findNodeById(treeData.value, id);
  treeEmint(isIfTree.value, findTree);
};
const DeleteUnitModal = () => {
  getTree();
  isIfTree.value = false;
  treeEmint(isIfTree.value);
  treeRef.value.rodList();
};

const exportClick = async () => {
  // const responseType = "blob"; // 设置响应类型为blob
  Modal.confirm({
    title: $t("exportTile"),
    icon: createVNode(ExclamationCircleOutlined),
    okText: $t('确认'),
    cancelText: $t('取消'),
    content: $t("exportContent"),
    onOk() {
      PostOrganizationExport(
        {
          enterpriseId: companyId.value,
          id: unitObj.value?.id,
        }
      ).then((res) => {
        let params = res.headers;
        let name = params["content-disposition"];
        let filename = name.split("=");
        const blob = new Blob([res.data], { type: "application/octet-stream" });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = filename[1]; // 设置下载文件名
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
      });
    },
    onCancel() {
      console.log('Cancel');
    },
    class: 'test',
  });
  
};

const ifEmployee = ref(false);
const employeeClose = (val) => {
  ifEmployee.value = val;
};
</script>
<style lang="scss" scoped>
.information {
  padding: 16px;
}
.treeCol {
  background-color: #f2f2f2;
}
::v-deep {
  .ant-breadcrumb li:last-child {
    color: #ff6c75;
  }
}
</style>
